<?php

abstract class Module {
	
	/*
	 * 添加module到调用树，由插件调用
	 */
	public static function addModule($module) {
		self::$modules[get_class($module)] = $module;
	}

	/*
	 * 直接执行指定Module
	 * @moduleName 模块名称
	 * @message 微信系统发来的Message类
	 * @material 素材xml
	 * @status 素材对应的用户状态
	 * @return 返回一个ReplyMessage类
	*/
	public static function doModule($moduleName, $message, $material, $userStatus) {
		Module::loadModule($moduleName);
		$module = self::$modules[$moduleName . 'Module'];
		if (!isset($module)) {
			$json = json_encode($userStatus);
			throw_exception("不存在的插件:$moduleName, userStatus:$json");
		}
		
		return $module->run($message, $material, $userStatus);
	}
	
	/*
	 * 调用插件的Call函数
	 */
	public static function callModule($moduleName, $user, $method, $params) {
		Module::loadModule($moduleName);
		$module = self::$modules[$moduleName . 'Module'];
		if (!isset($module)) {
			$json = json_encode($params);
			throw_exception("不存在的插件:$moduleName,方法：$method, 参数:$params");
		}
	
		return $module->call($user, $method, $params);
	}	
	
	/*
	 * 调用插件的activate函数
	*/
	public static function activateModule($moduleName) {
		Module::loadModule($moduleName);
		$module = self::$modules[$moduleName . 'Module'];
		if (!isset($module)) {
			// 激活的可能是模块不是插件
			//throw_exception("不存在的插件:$moduleName");
			return;
		}
	
		return $module->activate();
	}
	
	/*
	 * 添加扩展点
	 */
	public static function addHandle($handleName, $obj) {
		$array = $this->$handles[$handleName];
		foreach ($array as $handle) {
			if ($handle == $obj) {
				return;
			}
		}
		
		array_push($array, $obj);
	}
	
	/*
	 * 执行扩展点的所有操作
	 */
	public static function doHandle($handleName) {
		throw_exception('未实现');
	}

	/*
	 * 导入SQL，SQL文件在wx_Database，根据customId自动识别当前用户
	 * 调用前，如果超做的不是当前客户，则需要切换客户
	 */
	public static function importSQL($sqlPath, $dbCreate = FALSE) {
		
		if(!file_exists($sqlPath))
			return false;
		
		// parse content
		$content = file_get_contents($sqlPath);
		$content = str_replace("\r","\n",$content);
		$sqls = array();
		$aSql = explode(";\n",trim($content));

		// get sqls
		$num = 0;
		foreach($aSql as $sql){
			$sqls[$num]='';
			$queries = explode("\n",$sql);
			$queries = array_filter($queries);
			foreach($queries as $query){
				$str1 = substr($query,0,1);
				if($str1!=='#' && $str1!=='-') $sqls[$num].=$query;
			}
			$num++;
		}	
		unset($sql);
		
		// query sql
		if ($dbCreate) {
			try {
				$dsn = C('DB_TYPE').':host='.C('DB_HOST').';port='.C('DB_PORT');
				$pdo = new PDO($dsn, C('DB_USER'), C('DB_PWD'));
			
				foreach($sqls as $sql){
					$sql = str_replace(C('ORIGINAL_DB_PREFIX'), C('DB_PREFIX'), $sql);
					$pdo->exec($sql);
				}
			} catch (PDOException $e) {
				throw_exception("DB ERROR: ". $e->getMessage());
			}
		} else {
			$model = new Model();
			foreach($sqls as $sql){
				$sql = str_replace(C('ORIGINAL_DB_PREFIX'), C('DB_PREFIX'), $sql);
				$model->query($sql);
			};
		}

		return true;
	}
	
	/*
	 * 装载指定模块
	 */
	protected static function loadModule($moduleName) {
		$path = module_class_path($moduleName);
		if (!file_exists($path))
			return false;

		include_once $path;
		return true;
	}
	
	/*
	 * 装载指定的php
	 */
	protected static function includePhp($moduleName, $php, $ext = 'class.php') {
		$path = module_php_path($moduleName, $php, $ext);
		if (!file_exists($path)) {
			Log::write("php不存在:$path");
			return false;
		}
		
		include_once $path;
		return true;
	}
	
	/*
	 * 获取所有插件名称
	 */
	public static function moduleAll(){
		$path = MODULE_BASE_PATH;
		
		if(!is_dir($path)){
			return array();
		}
	
		$arr = array();
		$hd = opendir($path);
		while(($file = readdir($hd))!==false){
			if('.' == substr($file, 0, 1))
				continue;
	
			if(is_dir($path."/".$file)){
				array_push($arr, $file);
			}
		}
		closedir($hd);
		return $arr;
	}
	
	/*
	 * 获取指定插件数据
	 */
	public static function moduleData($moduleName){
		$default_headers = array(
				'Name' => 'Module Group Name',
				'Group' => 'Module Group',
				'Version' => 'Version',
				'Description' => 'Description',
				'Author' => 'Author',
				'Iconurl' => 'Iconurl',
				'Modules' => 'Modules',
				'Display' => 'Display',
		);
		
		$path = module_class_path($moduleName);		
		$plugin_data = get_file_data( $path, $default_headers );
		return $plugin_data;
	}
	
	/*
	 * 激活指定客户的插件，需插件实现（可选）
	 */
	public function activate() {
		Log::write(get_class($this).'activate');		
	}
	
	/*
	 * 取消激活指定客户的插件，需插件实现（可选）
	 */
	public function deactivate() {
		Log::write(get_class($this).'deactivate');
	}
	
	/*
	 * 运行模块，由Callback调用，需插件实现
	 */
	public function run($message, $material, $status) {
		throw_exception('不可调用基类run');
	}
	
	/*
	 * 调用插件资源，需插件实现（可选）
	 */
	public function call($user, $method, $param) {
		Log::write(get_class($this).' call');
	}
	
	/*
	 * 存储所有的Module
	*/
	private static $modules = array();
	
	/*
	 * 存储所有的扩展点
	*/
	private static $handles = array(module_handle_text => array(),
				
	);
}